package com.example.backendmanage.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.backendmanage.info.UploadFile;
import com.example.backendmanage.mapper.FileMapper;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件上传的接口
 *
 * */
@RestController
@RequestMapping("/file")
public class FileController {
    //引入下载路径
    @Value("${files.upload.path}")
    private String FileUploadPath;

    @Autowired
    private FileMapper fileMapper;

    @RequestMapping("/upload")
    public String upload(@RequestParam MultipartFile multipartFile){
        try {
            //获取原来的名字
            String originalFileName=multipartFile.getOriginalFilename();
            //获取文件类型
            String type= FileUtil.extName(originalFileName);
            long fileSize=multipartFile.getSize();
            //将文件存储到磁盘里面去
            File uploadParentFile=new File(FileUploadPath);
            if (!uploadParentFile.exists()){
                uploadParentFile.mkdir();
            }
            //定义唯一的文件表示码
            String uuid= IdUtil.fastSimpleUUID();
            String fileAndUid=uuid+ StrUtil.DOT+type;
            File uploadPath=new File(FileUploadPath+fileAndUid);
            String url=null;
            String md5=null;
            //上传文件到磁盘
            multipartFile.transferTo(uploadPath);
            //获取文件的md即唯一标识符，作用是当磁盘中存在相同的图片的时候就可以只存在一张图片
            md5=SecureUtil.md5(uploadPath);
            //从数据库查询是否有相同的记录
            UploadFile checkFile=fileMapper.findByMD5(md5);
            if (checkFile!=null){
                url=checkFile.getUrl();
                md5=null;
                //删除文件
                uploadPath.delete();
            }else {
                url="http://localhost:8081/file/"+fileAndUid;
            }
            //存储到数据库里面
            UploadFile uploadFile=new UploadFile();
            uploadFile.setName(originalFileName);
            uploadFile.setSize(fileSize);
            uploadFile.setType(type);
            uploadFile.setUrl(url);
            uploadFile.setMd5(md5);
            fileMapper.insert(uploadFile);
            return url;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/{fileAndUid}")
    public void download(@PathVariable String fileAndUid, HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            // 根据文件唯一标识码获得文件
            File uploadFile=new File(FileUploadPath+fileAndUid);
            //设置文件输出格式
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String filename= null;
            filename = URLEncoder.encode(fileAndUid,"UTF-8");
            response.setHeader("Content-Disposition","attachment;filename="+filename);
            //将文件输出出去
            //读取文件字节流
            out = response.getOutputStream();
            out.write(FileUtil.readBytes(uploadFile));
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
